package com.atguigu.crowd.funding.handler;

import com.atguigu.crowd.funding.entity.Meun;
import com.atguigu.crowd.funding.entity.ResultEntity;
import com.atguigu.crowd.funding.service.api.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hftang
 * @date 2019-10-30 10:08
 * @desc
 */
@RestController
public class MeunHandler {
    @Autowired
    private MenuService menuService;

    @RequestMapping("/menu/update")
    public ResultEntity<String> updateMenu(Meun menu) {

        menuService.updateMenu(menu);

        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/get/{menuId}")
    public ResultEntity<Meun> getMenuById(@PathVariable("menuId") Integer menuId) {

        Meun menu = menuService.getMenuById(menuId);

        return ResultEntity.successWithData(menu);
    }

    @RequestMapping("/menu/save")
    public ResultEntity<String> saveMenu(Meun menu) {

        menuService.saveMenu(menu);

        return ResultEntity.successWithoutData();
    }


    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Meun> getWholeTree() {
        List<Meun> meunList = this.menuService.getAll();
        //然后组装返回一个完成meun
        Map<Integer, Meun> hashMap = new HashMap<>();

        Meun rootNode = null;

        for (Meun meun : meunList) {
            Integer id = meun.getId();
            hashMap.put(id, meun);
        }

        for (int i = 0; i < meunList.size(); i++) {
            Meun meun = meunList.get(i);
            Integer pid = meun.getPid();
            if (pid == null) {
                //这就是根节点
                rootNode = meun;
                continue;
            }
            //如果pid不为空的话 查他的父亲
            Meun afterMeun = hashMap.get(pid);
            afterMeun.getChildren().add(meun);
        }


        return ResultEntity.successWithData(rootNode);
    }
}
